<?php
class Tool_Array
{
    /**
     * 从对象(或数组)中提取指定字段的值
     */
    public static function getFields($objs, $key)
    {
        $ids = array();
        if (is_array($objs))
        {
            foreach($objs as $obj)
            {
                if (is_array($obj))
                {
                    $ids[] = $obj[$key];
                }
                else if (is_object($obj))
                {
                    $ids[] = $obj->$key;
                }
                else
                {
                    $ids[] = $obj;
                }
            }
        }
        return $ids;
    }

    public function list2Map(array $list, $key, $value_key=null)
    {
        if(empty($list))
        {
            return array();
        }

        $map = array();
        foreach($list as $item)
        {
            if ($value_key !== null)
            {
                $map[$item[$key]] = $item[$value_key];
            }
            else
            {
                $map[$item[$key]] = $item;
            }
        }
        return $map;
    }

    public function filterEmpty(&$list)
    {
        if (!empty($list) && is_array($list))
        {
            foreach ($list as $idx => $item)
            {
                if (empty($item))
                {
                    unset($list[$idx]);
                }
            }
        }
        return $list;
    }

    public function sortByField(&$arr, $fieldName, $flag='desc')
    {
        $indexArr = array();
        foreach ($arr as $idx=>$item)
        {
            $indexArr[$idx] = $item[$fieldName];
        }

        if ('desc' == $flag)
        {
            arsort($indexArr);
        }
        else
        {
            asort($indexArr);
        }

        $result = array();
        foreach ($indexArr as $idx=>$field)
        {
            $result[$idx] = $arr[$idx];
        }
        $arr = $result;
    }
}
?>